﻿package test;

import java.lang.reflect.Method;

/**
 * 反射一:动态生成类,动态调用方法
 * */
public class LangDemo2 {
	public static void main(String[] args) throws Exception {
		Class<?> c = Class.forName("com.javase.lang.demo.Person");
		// 实例化对象
		Object obj = c.newInstance();
		Method m1 = c.getMethod("sayHello", String.class);
		m1.invoke(obj, "Merry");
		Method m2 = c.getMethod("setName", String.class);
		Method m3 = c.getMethod("setAge", int.class);
		// 动态设值
		m2.invoke(obj, "Jack");
		m3.invoke(obj, 25);
		Method m4 = c.getMethod("getName");
		Method m5 = c.getMethod("getAge");
		// 动态取值
		System.out.print(m4.invoke(obj)+":");
		System.out.println(m5.invoke(obj));
	}
}

class Person {
	private String name;
	private int age;

	public void sayHello(String name) {
		System.out.println("hello:" + name);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return this.name + ":" + this.age;
	}
}